import { NextResponse } from 'next/server'
import { logger } from './lib/logger'

export function middleware(request) {
  // Log API requests
  if (request.nextUrl.pathname.startsWith('/api/')) {
    logger.apiRequest({
      method: request.method,
      url: request.nextUrl.pathname,
      userAgent: request.headers.get('user-agent')
    })
  }

  // Handle CORS preflight requests
  if (request.method === 'OPTIONS') {
    return new NextResponse(null, {
      status: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      },
    })
  }

  return NextResponse.next()
}

export const config = {
  matcher: '/api/:path*'
}
